package com.theorydance.springsourcestudy.postprocessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.stereotype.Component;

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public MyBeanFactoryPostProcessor(){
        System.out.println("this is MyBeanFactoryPostProcessor()");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 获取BeanDefinitionRegistry
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

        // 创建一个新的BeanDefinition
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MyBean.class);

        // 将新的BeanDefinition添加到容器中
        registry.registerBeanDefinition("myBean", builder.getBeanDefinition());
    }

    public static class MyBean {
        public MyBean(){
            System.out.println("this is MyBean()");
        }
    }
}